package com.hyy.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        //1、启动类
        Channel channel = new Bootstrap()
                //2、添加 EventLoop
                .group(group)
                //3、选择客户端的channel的实现
                .channel(NioSocketChannel.class)
                //4、添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());

                    }
                })
                //5、连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                .sync()//阻塞方法，直到连接建立
                .channel();//代表连接对象
        log.debug("channel---- {}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if("q".equals(line)){
                    channel.close();
//                    log.debug("处理关闭连接后的一系列操作");//不能在此处调用
                    break;
                }
                channel.writeAndFlush(line);
            }


        }).start();

        //获取 closedFuture 对象  1）同步处理关闭  2）异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        // 1、同步处理关闭
//        closeFuture.sync();
//        log.debug("处理关闭连接后的一系列操作");
//        group.shutdownGracefully();
        //2、异步处理关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("处理关闭连接后的一系列操作");
                group.shutdownGracefully();
            }
        });
    }
}
